const fs = require('fs');
const path = require('path');
const CDPClient = require('./cdp-client');

class LogWriter extends CDPClient {
  constructor(host, port, options = {}) {
    super(host, port, options);
    this.logDir = options.logDir || 'logs';
    this.logFile = options.logFile || `cdp-${new Date().toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }).replace(/[\/:]/g, '-')}.log`;
    this.ensureLogDirectory();
  }

  ensureLogDirectory() {
    const logPath = path.join(process.cwd(), this.logDir);
    if (!fs.existsSync(logPath)) {
      fs.mkdirSync(logPath, { recursive: true });
    }
  }

  formatLogMessage(params) {
    const args = params.args.map(arg => {
      if (arg.type === 'string') return arg.value;
      if (arg.type === 'object') return JSON.stringify(arg.value);
      return arg.value;
    }).join(' ');

    return `${args}\n`;
  }

  async _attemptConnection() {
    await super._attemptConnection();

    // Override the Runtime.consoleAPICalled event handler
    this.client.on('Runtime.consoleAPICalled', (params) => {
      const logMessage = this.formatLogMessage(params);
      const logPath = path.join(process.cwd(), this.logDir, this.logFile);

      // Write to log file
      fs.appendFile(logPath, logMessage, (err) => {
        if (err) {
          console.error('[LogWriter] Error writing to log file:', err);
          this._notifyError(err);
        }
      });

      // Call parent class handlers
      this.messageHandlers.forEach(handler => handler(params));
    });
  }
}

module.exports = LogWriter;